module.exports = app => {
    const express = require('express')
    const CategoryModel = require('../../models/Category.js')
    const adminRouter = express.Router()

    app.use('/admin', adminRouter)

    // 新建分类
    adminRouter.post('/api/category', async(req, res) => {
        // 存入数据库
        const category = await CategoryModel.create(req.body)
        // 返回值
        res.send({
            code: 200,
            message: 'success',
            data: category
        })
    })

    // 分类列表
    adminRouter.get('/api/category', async(req, res) => {
        const category = await CategoryModel.find().populate('parent').limit(10)  // populate 用于填充 parent 数据, 再模型中定义好引用的数据模型
        res.send(category)
    })

    // 分类详情
    adminRouter.get('/api/category/:id', async(req, res) => {
        const model = await CategoryModel.findById(req.params.id)
        res.send(model)
    })

    // 修改分类
    adminRouter.put('/api/category/:id', async(req, res) => {
        // 存入数据库
        const category = await CategoryModel.findByIdAndUpdate(req.params.id, req.body)
        // 返回值
        res.send({
            code: 200,
            message: 'success',
            data: category
        })
    })

    // 删除分类
    adminRouter.delete('/api/category/:id', async(req, res) => {
        await CategoryModel.findByIdAndDelete(req.params.id)
        res.send(true)
    })
}